import {defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import {resolve} from 'path'
import vueJsx from '@vitejs/plugin-vue-jsx'

export default async ({mode}) => {
    const env = loadEnv(mode, process.cwd())
    const proxyPrefix = env.VITE_APP_PROXY_PREFIX
    let plugins = [vue(), vueJsx(),]
    if (env.VITE_APP_ENV === 'development') {
        let module = await import('vite-plugin-vue-devtools')
        plugins.push(module.default())
    }
    return defineConfig({
        base: env.VITE_APP_BASE,
        plugins: plugins,
        resolve: {
            alias: {
                '@': resolve(__dirname, 'src'),
                '@cps': resolve(__dirname, 'src/components'),
                'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
            },
        },

        build: {
            chunkSizeWarningLimit: 1500,
            sourcemap: true, // 确保生成 source maps
            rollupOptions: {
                output: {
                    entryFileNames: 'assets/[name]-[hash].js',
                    chunkFileNames: 'assets/[hash].js',
                    // manualChunks(id) {
                    //     if (id.includes('node_modules')) {
                    //         return id.toString().split("node_modules/")[1].split("/")[0].toString();
                    //     }
                    // }
                }
            }
        },
        esbuild: {
            pure: ['console.log'], // 删除 console.log
            drop: ['debugger'], // 删除 debugger
        },

        server: {
            host: '0.0.0.0',
            port: env.VITE_APP_PORT || process.env.port,
            proxy: {
                [proxyPrefix]: {
                    target: env.VITE_APP_BASE_URL,
                    changeOrigin: true,
                    ws: true,
                    toProxy: true,
                    rewrite: path => path.replace(new RegExp(`^${proxyPrefix}`), ''),
                },
                ['/csos']: {
                    target: env.VITE_APP_BASE_URL,
                    changeOrigin: true,
                    toProxy: true,
                    rewrite: path => path.replace(new RegExp(`^/csos`), '/'),
                },
                ['/rest']: {
                    target: env.VITE_APP_BASE_URL,
                    changeOrigin: true,
                    toProxy: true,
                    // rewrite: path => path.replace(new RegExp(`^/admin-api`), '/'),
                },
            },
        },
    })
}
